/**
 * @file: vscode
 * @author: v_xieyejiang
 * @Date: 2018-12-10 11:36:26
 * @Last Modified by: v_xieyejiang
 * @Last Modified time: 2018-12-10 12:48:38
 */

const express = require('express');
const app = express();
const path = require('path');
const cors = require('cors');
const colors = require('colors');
const config = require('./config');
const history = require('connect-history-api-fallback');
const router = require('./router');
const setRes = require('./utils/setRes');

const session = require('express-session');
const FileStore = require('session-file-store')(session);
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');

const resolve = dir => {
    return path.resolve(__dirname, dir);
};

if (process.env.NODE_ENV === 'development') {
    app.use(
        cors({
            credentials: true,
            origin: [`http://localhost:${config.port - 1}`]
        })
    );
}

const SESSION_CONFIG = {
    secret: 'JAYCE-NODE-SERVER',
    name: 'NodeSessionID',
    store: new FileStore({
        ttl: config.ttl // 会话时间（以毫秒为单位）
    }),
    resave: false,
    saveUninitialized: true,
    cookie: {
        maxAge: config.ttl // 会话时间（以毫秒为单位）
    }
};

app.use(bodyParser()); // ================== 1
app.use(session(SESSION_CONFIG)); // ======= 2
app.use(cookieParser()); // ================ 3
router(app); // ============================ 4

if (process.env.NODE_ENV !== 'development') {
    const staticFileMiddleware = express.static(resolve('../dist'));
    app.use(staticFileMiddleware);
    app.use(
        history({
            disableDotRule: true,
            verbose: true,
            rewrites: [
                {
                    from: /^\/apis\/.*$/,
                    to: resolve('../dist/index.html')
                },
                {
                    from: 'favicon.ico',
                    to: resolve('../dist/favicon.ico')
                }
            ]
        })
    );
    app.use(staticFileMiddleware);
}

app.listen(config.port, () => {
    global.console.log('服务已启动'.blue);
    global.console.log(`http://localhost:${config.port}`.blue);
    global.console.log(`http://127.0.0.1:${config.port}`.blue);
});
